package com.jd.basic.aop;

import com.jd.basic.anno.LogAnnotation;
import com.jd.basic.utils.HttpContextUtils;
import com.jd.basic.utils.IPUtils;
import com.jd.system.domain.Log;
import com.jd.system.service.LogService;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;

@Component
@Aspect
@Slf4j
public class LogAop {
    @Autowired
    private LogService logService;

    @Around("@annotation(com.jd.basic.anno.LogAnnotation)")
    public Object around(ProceedingJoinPoint pjp) throws Throwable {
        long beginTime = System.currentTimeMillis();
        // 执行方法
        Object result = pjp.proceed();
        // 执行时长
        Long time = System.currentTimeMillis() - beginTime;

        saveLog(pjp,time);

        return result;
    }
    public void saveLog(ProceedingJoinPoint pjp, Long time) throws Throwable {
        // 获取方法对象
        MethodSignature methodSignature = (MethodSignature) pjp.getSignature();
        Method method = methodSignature.getMethod();
        Log log = new Log();

        // 通过方法对象获取注解
        LogAnnotation annotation = method.getAnnotation(LogAnnotation.class);
        if (annotation != null) {
            log.setMethodDes(annotation.value());
            String value = annotation.value();
            if ("添加".contains(value)){

            }
        }
        String methodName = methodSignature.getName();
        log.setMethodName(methodName);
        // 获取ip
        HttpServletRequest httpServletRequest = HttpContextUtils.getHttpServletRequest();
        log.setIp(IPUtils.getIpAddr(httpServletRequest));
        log.setExecutionTime(time);
        logService.add(log);

    }
}
